package com.lyhdev.android.touchenglish;

import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class ServiceFactory {
	private String apiUrl = "http://android.lyhdev.com/TouchEnglish/api/";

	private final static String TAG = "TouchEnglish_ServiceFactory";

	private HashMap<String, TEChannel> channelCached = new HashMap<String, TEChannel>();

	// DESIGN PATTERN IMPL: SINGLETON
	private static ServiceFactory __singleton__ = null;

	public static ServiceFactory getInstance() {
		if (__singleton__ == null) {
			__singleton__ = new ServiceFactory();
		}
		return __singleton__;
	}

	public JSONObject quiz(String id) {
		String urlstr = apiUrl.concat("quiz?id=").concat(id);

		Log.i(TAG, String.format("urlstr=\"%s\"", urlstr));

		String dump = httpdump(urlstr);

		Log.i(TAG, String.format("dump=\"%s\"", dump));

		JSONObject result = null;

		try {
			result = new JSONObject(dump);
			Log.i(TAG, String.valueOf(result.get("errno")));
		} catch (JSONException ex) {
			Log.e(TAG, ex.getMessage());
		}

		return result;
	}

	public TEChannel channel(String ch) {
		if (channelCached.containsKey(ch)) {
			return channelCached.get(ch);
		} else {
			TEChannel channel = newChannel(ch);
			channelCached.put(ch, channel);
			return channel;
		}
	}

	private TEChannel newChannel(String ch) {
		String urlstr = apiUrl.concat("channel?ch=").concat(ch);
		String dump = httpdump(urlstr);

		TEChannel channel = new TEChannel();

		try {
			JSONObject json = new JSONObject(dump);
			String errno = String.valueOf(json.get("errno"));
			if (errno.equals("0")) {
				Object obj = json.get("quiz");
				if (obj != null && obj instanceof JSONArray) {
					JSONArray quizX = (JSONArray) obj;

					for (int i = 0; i < quizX.length(); i++) {
						Object obj2 = quizX.get(i);
						if (obj2 != null && obj2 instanceof JSONObject) {
							JSONObject quizZ = (JSONObject) obj2;

							TEQuiz quiz = new TEQuiz();
							quiz.setText(quizZ.getString("text"));
							quiz.setImage(quizZ.getString("image"));
							quiz.setSound(quizZ.getString("sound"));
							quiz.parseOptions(quizZ.getString("options"));

							channel.addQuiz(quiz);
						}
					}
				}
			}
		} catch (JSONException ex) {
			Log.e(TAG, ex.getMessage());
		}

		channel.cacheAllImage();
		return channel;
	}

	/**
	 * Dump HTTP responses to string.
	 * 
	 * @param urlstr
	 * @return
	 */
	private String httpdump(String urlstr) {
		StringBuilder result = new StringBuilder();

		try {
			URL url = new URL(urlstr);
			URLConnection conn = url.openConnection();
			conn.connect();

			InputStreamReader reader = new InputStreamReader(
					conn.getInputStream(), "UTF-8");

			int c = -1;
			while ((c = reader.read()) != -1) {
				result.append((char) c);
			}
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage());
		}

		return result.toString();
	}

	private QuizSoundPlayer __player = null;

	/**
	 * Play sound using common MediaPlayer.
	 * 
	 * @param quiz
	 */
	public synchronized void playSound(TEQuiz quiz) {
		//prevent multiple sound play in the same time.
		if (__player != null) {
			__player.stop();
		}
		__player = new QuizSoundPlayer(quiz);
		new Thread(__player).start();
	}
}
